package marshall;


import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.ByteInput;
import org.jboss.marshalling.Unmarshaller;

public class MarshallingDecoder {

    private final Unmarshaller unmarshaller;

    public MarshallingDecoder()throws Exception{
        this.unmarshaller = MarshallingCodecFactory.buildUnmarshalling();
    }

    public Object decode(ByteBuf in)throws Exception {
        int objectSize = in.readInt();
        System.out.println(objectSize);
        System.out.println(in.readerIndex());
        ByteBuf buf = in.slice(in.readerIndex(), objectSize);
        ByteInput input = new ChannelBufferByteInput(buf);
        try {
            unmarshaller.start(input);
            Object obj = unmarshaller.readObject();
            unmarshaller.finish();
            in.readerIndex(in.readerIndex() + objectSize);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            unmarshaller.close();
        }
        return null;
    }
}
